﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models.PlatForm.Dtos.Database;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 数据管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018.02.03
    /// </summary>
    [Route("api/PlatForm/[controller]")]
    public class DatabaseController : BaseApiController
    {
        private DatabaseBll databaseServiceBll = new DatabaseBll();

        #region GET
        /// <summary>
        /// 表名列表
        /// </summary>
        /// <param name="id">连接Id</param>
        /// <param name="input">过滤条件</param>
        /// <returns></returns>
        [HttpGet("{id}/Tables")]
        public async Task<ResponseResult> GetList(string id, [FromQuery] KeywordInput input)
        {
            try
            {
                var data = await databaseServiceBll.GetList(id);
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    data = data.FindAll(d => d.Table.Contains(input.keyword) || d.TableName.Contains(input.keyword));
                }
                var output = data.MapToList<DatabaseTableListOutput>();
                return Success(new { list = output });
            }
            catch (Exception ex)
            {
                var data = new List<DatabaseTableListOutput>();
                return Success(new { list = data });
            }
        }

        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <param name="DBId">连接Id</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        [HttpGet("{DBId}/Table/{tableName}/Preview")]
        public async Task<ResponseResult> GetData([FromQuery] DatabaseTablePreviewQuery input, string DBId, string tableName)
        {
            var pageinput = input.MapTo<PageInput>();
            pageinput.queryJson = new { input.field }.ToJson();
            var data = await databaseServiceBll.GetData(DBId, tableName, pageinput);
            return Success(data);
        }

        /// <summary>
        /// 字段列表
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        [HttpGet("{DBId}/Tables/{tableName}/Fields")]
        public async Task<ResponseResult> GetFieldList(string DBId, string tableName)
        {
            var data = (await databaseServiceBll.GetFieldList(DBId, tableName)).MapToList<DatabaseTableFieldsListOutput>();
            return Success(new { list = data });
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="tableName">主键值</param>
        /// <returns></returns>
        [HttpGet("{DBId}/Table/{tableName}")]
        public async Task<ResponseResult> GetInfo(string DBId, string tableName)
        {
            var data = new DatabaseTableInfoOutput()
            {
                tableInfo = (await databaseServiceBll.GetList(DBId)).Find(m => m.Table == tableName).MapTo<TableInfo>(),
                tableFieldList = (await databaseServiceBll.GetFieldList(DBId, tableName)).MapToList<TableFieldList>()
            };
            return Success(data);
        }

        /// <summary>
        /// 获取数据库表字段下拉框列表
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        [HttpGet("{DBId}/Tables/{tableName}/Fields/Selector")]
        public async Task<ResponseResult> SelectorData(string DBId, string tableName)
        {
            var data = (await databaseServiceBll.GetList(DBId)).FindAll(m => m.Table == tableName).MapToList<DatabaseTableFieldsSelectorOutput>();
            return Success(new { list = data });
        }
        #endregion

        #region POST
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        [HttpDelete("{DBId}/Table/{tableName}")]
        public async Task<ResponseResult> Delete(string DBId, string tableName)
        {
            if ((await databaseServiceBll.GetList(DBId)).Find(m => m.Table == tableName).Sum == 0)
            {
                string[] byoTable = "base_authorize,base_billrule,base_dbbackup,base_dblink,base_dictionarydata,base_dictionarytype,base_imcontent,base_languagemap,base_languagetype,base_menu,base_message,base_messagereceive,base_module,base_modulebutton,base_modulecolumn,base_moduledataauthorize,base_moduledataauthorizescheme,base_organize,base_position,base_province,base_role,base_sysconfig,base_syslog,base_timetask,base_timetasklog,base_user,base_userrelation,crm_busines,crm_businesproduct,crm_clue,crm_contract,crm_contractinvoice,crm_contractmoney,crm_contractproduct,crm_customer,crm_customercontacts,crm_followlog,crm_invoice,crm_product,crm_receivable,ext_bigdata,ext_document,ext_documentshare,ext_emailconfig,ext_emailreceive,ext_emailsend,ext_employee,ext_order,ext_orderentry,ext_orderreceivable,ext_projectgantt,ext_schedule,ext_tableexample,ext_worklog,ext_worklogshare,flow_delegate,flow_engine,flow_engineform,flow_enginevisible,flow_task,flow_taskcirculate,flow_tasknode,flow_taskoperator,flow_taskoperatorrecord,wechat_mpeventcontent,wechat_mpmaterial,wechat_mpmessage,wechat_qydepartment,wechat_qymessage,wechat_qyuser,wform_applybanquet,wform_applydelivergoods,wform_applydelivergoodsentry,wform_applymeeting,wform_archivalborrow,wform_articleswarehous,wform_batchpack,wform_batchtable,wform_conbilling,wform_contractapproval,wform_contractapprovalsheet,wform_debitbill,wform_documentapproval,wform_documentsigning,wform_expenseexpenditure,wform_finishedproduct,wform_finishedproductentry,wform_incomerecognition,wform_leaveapply,wform_letterservice,wform_materialrequisition,wform_materialrequisitionentry,wform_monthlyreport,wform_officesupplies,wform_outboundorder,wform_outboundorderentry,wform_outgoingapply,wform_paydistribution,wform_paymentapply,wform_postbatchtab,wform_procurementmaterial,wform_procurementmaterialentry,wform_purchaselist,wform_purchaselistentry,wform_quotationapproval,wform_receiptprocessing,wform_receiptsign,wform_rewardpunishment,wform_salesorder,wform_salesorderentry,wform_salessupport,wform_staffovertime,wform_supplementcard,wform_travelapply,wform_travelreimbursement,wform_vehicleapply,wform_violationhandling,wform_warehousereceipt,wform_warehousereceiptentry,wform_workcontactsheet".Split(',');
                bool exists = ((IList)byoTable).Contains(tableName.ToLower());
                if (exists)
                {
                    return Error("系统自带表,不允许被删除");
                }
                else
                {
                    await databaseServiceBll.Delete(DBId, tableName);
                    return Success("删除成功");
                }
            }
            else
            {
                return Error("表已经被使用,不允许被删除");
            }
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpPost("{DBId}/Table")]
        public async Task<ResponseResult> Create(string DBId, [FromBody] DatabaseTableCrInput input)
        {
            try
            {
                if ((await databaseServiceBll.GetList(DBId)).Find(m => m.Table == input.tableInfo.newTable).IsNotEmptyOrNull())
                {
                    return Error("表已存在");
                }
                var tableInfo = input.tableInfo.MapTo<DbTableModel>();
                tableInfo.Table = input.tableInfo.newTable;
                var tableFieldList = input.tableFieldList.MapToList<DbTableFieldModel>();
                await databaseServiceBll.Create(DBId, tableInfo, tableFieldList);
                return Success("新建成功");
            }
            catch (Exception ex)
            {
                return Error(ex.InnerException.Message);
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="DBId">连接Id</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpPut("{DBId}/Table")]
        public async Task<ResponseResult> Update(string DBId, [FromBody] DatabaseTableUpInput input)
        {
            try
            {
                var tableInfo = input.tableInfo.MapTo<DbTableModel>();
                tableInfo.Table = input.tableInfo.newTable;
                var tableFieldList = input.tableFieldList.MapToList<DbTableFieldModel>();
                if ((await databaseServiceBll.GetList(DBId)).Find(m => m.Table == input.tableInfo.table).Sum == 0)
                {
                    string[] byoTable = "base_authorize,base_billrule,base_dbbackup,base_dblink,base_dictionarydata,base_dictionarytype,base_imcontent,base_languagemap,base_languagetype,base_menu,base_message,base_messagereceive,base_module,base_modulebutton,base_modulecolumn,base_moduledataauthorize,base_moduledataauthorizescheme,base_organize,base_position,base_province,base_role,base_sysconfig,base_syslog,base_timetask,base_timetasklog,base_user,base_userrelation,crm_busines,crm_businesproduct,crm_clue,crm_contract,crm_contractinvoice,crm_contractmoney,crm_contractproduct,crm_customer,crm_customercontacts,crm_followlog,crm_invoice,crm_product,crm_receivable,ext_bigdata,ext_document,ext_documentshare,ext_emailconfig,ext_emailreceive,ext_emailsend,ext_employee,ext_order,ext_orderentry,ext_orderreceivable,ext_projectgantt,ext_schedule,ext_tableexample,ext_worklog,ext_worklogshare,flow_delegate,flow_engine,flow_engineform,flow_enginevisible,flow_task,flow_taskcirculate,flow_tasknode,flow_taskoperator,flow_taskoperatorrecord,wechat_mpeventcontent,wechat_mpmaterial,wechat_mpmessage,wechat_qydepartment,wechat_qymessage,wechat_qyuser,wform_applybanquet,wform_applydelivergoods,wform_applydelivergoodsentry,wform_applymeeting,wform_archivalborrow,wform_articleswarehous,wform_batchpack,wform_batchtable,wform_conbilling,wform_contractapproval,wform_contractapprovalsheet,wform_debitbill,wform_documentapproval,wform_documentsigning,wform_expenseexpenditure,wform_finishedproduct,wform_finishedproductentry,wform_incomerecognition,wform_leaveapply,wform_letterservice,wform_materialrequisition,wform_materialrequisitionentry,wform_monthlyreport,wform_officesupplies,wform_outboundorder,wform_outboundorderentry,wform_outgoingapply,wform_paydistribution,wform_paymentapply,wform_postbatchtab,wform_procurementmaterial,wform_procurementmaterialentry,wform_purchaselist,wform_purchaselistentry,wform_quotationapproval,wform_receiptprocessing,wform_receiptsign,wform_rewardpunishment,wform_salesorder,wform_salesorderentry,wform_salessupport,wform_staffovertime,wform_supplementcard,wform_travelapply,wform_travelreimbursement,wform_vehicleapply,wform_violationhandling,wform_warehousereceipt,wform_warehousereceiptentry,wform_workcontactsheet".Split(',');
                    bool exists = ((IList)byoTable).Contains(input.tableInfo.table.ToLower());
                    if (exists)
                    {
                        return Error("系统自带表,不允许被修改");
                    }
                    else
                    {
                        await databaseServiceBll.Update(DBId, input.tableInfo.table, tableInfo, tableFieldList);
                        return Success("修改成功");
                    }
                }
                else
                {
                    return Error("表已经被使用,不允许被编辑");
                }
            }
            catch (Exception ex)
            {
                return Error(ex.InnerException.Message);
            }
        }
        #endregion
    }
}
